<template>
  <div>
    <PageTitle :title="titleName"></PageTitle>
    <div class="form-wrapper">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="class_name">
          <el-input v-model="ruleForm.class_name" placeholder="请输入类别名称"></el-input>
        </el-form-item>
        <el-form-item label="分类状态" prop="state">
          <el-select v-model="ruleForm.state" placeholder="请选择类别状态">
            <el-option label="上架" value="2"></el-option>
            <el-option label="下架" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import PageTitle from '@/components/pageTitle/PageTitle.vue'
  import _ from 'lodash'
  export default {
    name: 'GoodsTypeAdd',
    components: {
      PageTitle
    },
    activated() {
      if(this.$route.params.id != 'none') {
        this._get()
      }
    },
    deactivated() {
      this.$destroy()
    },
    data() {
      return {
        ruleForm: {
          class_name: '',
          state: ''
        },
        rules: {
          class_name: [
            { required: true, message: '请输入类别名称', trigger: 'blur' }
          ],
          state: [
            { required: true, message: '请选择类别状态', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      titleName() {
        return this.$route.params.id == 'none' ? '添加商品分类' : '查看商品分类'
      },
      submitUrl() {
        return this.$route.params.id == 'none' ? this.$api + '/v1/fication/fication' : this.$api + '/v1/fication/modify'
      }
    },
    methods: {
      submitForm: _.throttle(function() {
        this.$refs.ruleForm.validate(async (valid) => {
          if(!valid) {
            return false
          }
          
          let {data: {code, data, msg}} = await this.$axios({
            url: this.submitUrl,
            method: 'POST',
            data: {
              id: this.$route.params.id,
              class_name: this.ruleForm.class_name,
              state: this.ruleForm.state
            }
          })
          
          if(code == 0) {
             this.$message.success('操作成功！')
             setTimeout(() => {
               this.$router.go(-1)
             }, 2000)
          }
        })
      },2000,{
        trailing: false
      }),
      async _get() {
        let {data: {code, data, msg}} = await this.$axios({
          url: this.$api + '/v1/fication/surface' ,
          method: 'GET',
          params: {
            id: this.$route.params.id
          }
        })
        
        if(code == 0) {
          this.ruleForm.class_name = data[0].class_name
          this.ruleForm.state = data[0].state
        }
      }
    }
  }
</script>

<style>
</style>
